const path = require('path');
const fs = require('fs');

if (!think.isExist(path.join(think.ROOT_PATH, 'www/userImages'))) {
  think.mkdir(path.join(think.ROOT_PATH, 'www/userImages'), '0777');
}

module.exports = class extends think.Service {
  async getUserOrgName(userId) {
    try {
      const org = think.model('userinfo/org');
      const userorg = think.model('userinfo/userorg');
      const { orgId } = await userorg.where({ userId }).field('orgId').find();
      const { name } = await org.where({ id: orgId }).field('name').find();
      return name;
    } catch (error) {
      think.logger.debug(error);
    }
  }

  async getUserOrg(userId) {
    try {
      const org = think.model('userinfo/org');
      const userorg = think.model('userinfo/userorg');
      const { orgId } = await userorg.where({ userId }).field('orgId').find();
      const { id, pid, name } = await org.where({ id: orgId }).field('id,pid,name').find();
      return { id, pid, name };
    } catch (error) {
      think.logger.debug(error);
    }
  }
  async getUserImg(userData) {
    const picture = think.model('picture');
    for (let index = 0; index < userData.length; index++) {
      const e = userData[index];
      let pictureUrl;
      if (!e.pictureid) {
        pictureUrl = '';
      } else {
        const pictureList = await picture.where(`id = ${e.pictureid}`).find();
        const imgBuffer = Buffer.from(pictureList.data, 'base64');
        const imgFilePath = path.join(think.ROOT_PATH, 'www/userImages', `${pictureList.name}`);
        fs.writeFileSync(imgFilePath, imgBuffer);
        pictureUrl = path.join('userImages', `${pictureList.name}`);
      }
      delete e.pictureid;
      e.pictureUrl = pictureUrl;
    }
    return userData;
  }
};
